import { ref, reactive, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import apis from '@/apis'
import { useUserStore } from '@/stores'
import { ZYL_WKSDK } from '@/utils/WKSDK'
import type { LoginTypes } from '@/types/login'
import { ElMessageBox, ElMessage } from 'element-plus'
/**
 * 登录功能自定义 hook
 * @returns {{
 *   account: import('vue').Ref<string>,
 *   password: import('vue').Ref<string>,
 *   login: () => Promise<void>
 * }} 返回登录状态和方法
 */
const useLogin = () => {
  const userStore = useUserStore()
  const account = ref<string>('13025268420')
  const password = ref<string>('123456')
  const router = useRouter()
  const route = useRoute()
  const agreed = ref<boolean>(false)
  const countryCode = ref<string>('+86')
  const countdown = ref<number>(0)
  const loginFormRef = ref<HTMLFormElement>()
  const registerFormRef = ref<HTMLFormElement>()
  //手机号登陆
  const loginForm: LoginTypes['loginForm'] = reactive({
    username: account.value,
    password: password.value,
  })
  const rules: LoginTypes['rules'] = reactive({
    username: [
      { required: true, message: '请输入您的账号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' },
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 10, message: '长度应该在6~10个字符之间' },
    ],
  })
  // 验证码
  const registerForm: LoginTypes['registerFormRef'] = reactive({
    phone: '',
    verifyCode: '',
  })
  const registerRules: LoginTypes['ruless'] = reactive({
    phone: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
    ],
    verifyCode: [
      { required: true, message: '请输入验证码', trigger: 'blur' },
      { len: 6, message: '验证码长度为6位', trigger: 'blur' },
    ],
  })

  const login = async () => {
    //检查是否勾选用户协议
    if (!agreed.value) {
      ElMessageBox.alert('请先阅读并同意用户协议', '提示', {
        confirmButtonText: '确定',
        callback: () => {
          // 自动聚焦到协议复选框
          document.querySelector('.agreement-checkbox')?.scrollIntoView({
            behavior: 'smooth',
            block: 'center',
          })
        },
      })
      return
    }

    await loginFormRef.value!.validate()
    const { query } = route
    const [res, err] = await apis.login({
      accountOrPhone: account.value,
      password: password.value,
    })

    console.log(res, err)
    if (err) return window.$message.error('登录失败')
    userStore.token = res.data.accessToken
    userStore.refreshToken = res.data.refreshToken
    userStore.userInfo = res.data.user

    if (res.data.families.length)
      userStore.userClanList = res.data.families.map((item: STORE.UserClanOrCouncilItem) => {
        return {
          ...item,
          role: userStore.USER_CLAN_ROLE_LIST[+item! - 1],
        }
      })

    if (res.data.councils.length)
      userStore.userCouncilList = res.data.councils.map((item: STORE.UserClanOrCouncilItem) => {
        return {
          ...item,
          role: userStore.USER_COUNCIL_ROLE_LIST[+item! - 1],
        }
      })
    if (res.data.families.length) userStore.userClanList = res.data.families
    if (res.data.councils.length) userStore.userCouncilList = res.data.councils

    window.$message.success('登录成功,即将跳转')
    userStore.isLogin = true
    setTimeout(() => {
      if (query.redirect) {
        //如果是从别的页面拦截跳转过来的，跳回到登录前的页面
        router.replace({
          path: query.redirect as string,
        })
      } else {
        router.replace({
          path: '/indexHome',
        })
      }
    }, 500)
    //初始化WKSDK
    ZYL_WKSDK?.init(res.data.accessToken, res.data.user.id)

    // //登陆完后跳转
    //  setTimeout(() => {
    //     router.replace("/indexHome");
    //   }, 50);
  }

  //二维码
  function generateRandomString(length: number = 6): string {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    let result = ''

    for (let i = 0; i < length; i++) {
      const randomIndex = Math.floor(Math.random() * characters.length)
      result += characters[randomIndex]
    }
    return result
  }
  const isGettingQR = ref<boolean>(false)
  const QRcodeUrl = ref<string>('')
  let scene: string = ''
  const getWxQRCode = (): void => {
    scene = generateRandomString()
    console.log(scene)
    isGettingQR.value = true
    apis
      .getWxQRCode({
        scene,
      })
      .then((res: any) => {
        console.log(res)
        isGettingQR.value = false
        QRcodeUrl.value = res.data
        nextTick(() => {
          setInterval(() => {
            // getQrCodeStatus(scene);
          }, 10000)
        })
      })
  }

  const getWxToken = (scene: string): void => {
    apis.getWxToken({ scene: scene }).then((res: any) => {
      console.log(res)
    })
  }

  //发送验证码
  const sendVerifyCode = () => {
    if (!registerForm.phone) {
      ElMessage.warning('请先输入手机号码')
      return
    }

    // 开始倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)

    // 这里调用发送验证码的API
    ElMessage.success('验证码已发送')
  }

  // 处理注册
  const handleRegister = () => {
    registerFormRef.value?.validate((valid: any) => {
      if (valid) {
        // 这里处理注册逻辑
        ElMessage.success('注册/登录成功')
      }
    })
  }

  // 处理登录
  const handleLogin = () => {
    loginFormRef.value?.validate((valid: any) => {
      if (valid) {
        // 这里处理登录逻辑
        ElMessage.success('登录成功')
      }
    })
  }

  return {
    agreed,
    loginForm,
    loginFormRef,
    rules,
    QRcodeUrl,
    isGettingQR,
    countryCode,
    countdown,
    registerRules,
    registerForm,
    registerFormRef,
    login,
    getWxQRCode,
    getWxToken,
    sendVerifyCode,
    handleRegister,
    handleLogin,
  }
}

export default useLogin
